package com.example.it.studybroadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

public class HomeActivity extends AppCompatActivity {

    private NetWorkReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        //创建一个意图过滤器
        IntentFilter filter = new IntentFilter();
        //接收网络改变的action
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

        receiver = new NetWorkReceiver();

        this.registerReceiver(this.receiver, filter);
    }

    public void sendNormalBroadcast(View view) {
        Intent intent = new Intent();
        intent.putExtra("MyKey", "我是自定义发送的广播");
        //放我我们Action，用来区分其他广播，注意Acting不要和系统的广播重复
        intent.setAction("com.example.it.studybroadcast.CustomBroadcast");
        this.sendBroadcast(intent);
    }

    /*
    * 发送一个有序广播
    * */
    public void sendOrderedBroadcast(View view) {
        Intent intent = new Intent();
        intent.setAction("com.example.it.studybroadcast.MyOrderedBroadcast");
        //放入一些数据
        intent.putExtra("MyKey", "MyKeyVlaue");
        /*
        * 参数:
        * intent： 我们发送的意图
        * receiverPermission: 广播接收者必须有的权限
        * */
        this.sendOrderedBroadcast(intent, null);
    }

    /*
    * 取消注册
    * */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(this.receiver);
    }

    public class NetWorkReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            //如果当前有默认的网络就返回NetworkInfo 否则就返回 null
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            //因为可能是null 所以要先判断是否为空
            if (networkInfo != null && networkInfo.isAvailable()) {
                if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    Toast.makeText(context, "Wifi", Toast.LENGTH_SHORT).show();

                } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    Toast.makeText(context, "流量", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(context, "世界上最遥远的距离就是没有网", Toast.LENGTH_SHORT).show();
            }
        }
    }


}
